import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Login,
    name: 'Login'
  },
  {
    path: '/main',
    name: 'Main',
    component: () => import(/* webpackChunkName: "main" */ '../views/Main.vue'),
    children: [
      {
        path: 'user_students',
        name: 'user_students',
        component: () => import(/* webpackChunkName: "user_student" */ '../views/user/Student.vue')
      },
      {
        path: 'user_teachers',
        name: 'user_teachers',
        component: () => import(/* webpackChunkName: "user_teacher" */ '../views/user/Teacher.vue')
      },
      {
        path: 'user_assistteacher',
        name: 'user_AssistTeacher',
        component: () => import(/* webpackChunkName: "user_teacher" */ '../views/user/AssistTeacher.vue')
      },
      {
        path: 'teach_course_coursemanage',
        name: 'Teach_Course_CourseManage',
        component: () => import(/* webpackChunkName: "Teach_Course_CourseManage" */ '../views/teach/course/CourseManage.vue')
      },
      {
        path: 'teach_course_coursecatagory',
        name: 'Teach_Course_CourseCatagory',
        component: () => import(/* webpackChunkName: "Teach_Course_CourseCatagory" */ '../views/teach/course/CourseCatagory.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局，每次跳转之前都会调用
router.beforeEach((to, from, next) => {
  // to ，对象，将要去的路由对象
  // from , 对象，从哪去的路由对象
  // next，函数
  //      next()  ：允许通过
  //      next(false)  ：不允许通过，不动，没反应
  //      next({name: 'Login'})   ： 重定向，跳转到指定的地址

  // 1. 判断是否是去登录页面
  if (to.name === 'Login') {
    next()
  } else {
    // 2. 判断当前 vuex 中是否有数据
    if (store.state.user) {
      // 如果有信息就通过
      next()
    } else {
      // 否则跳转到登录页面
      next({ name: 'Login' })
    }
  }
})

export default router
